const user = {
  // name: 'haha'
  name: '<script/>'
};

const vm = require('vm');

const templateMap = {
  templateA: '`<h2>${_(user.name)}</h2>`', //fs.readFile
  templateB: '`<p>hahahah</p>`'
};

const context = {
  user
  //↓ xss过滤函数
  , _:function(markup){
    if(!markup) return '';
    return String(markup)
      .replace(/&/g,'&amp;')
      .replace(/</g,'&lt;')
      .replace(/>/g,'&gt;')
      .replace(/'/g,'&#39;')
      .replace(/""/g,'&quot;')
  }
  , include: function (name) {
    return templateMap[name]
  }
};

Object.keys(templateMap).forEach(key => {
  const temp = templateMap[key];
  templateMap[key] = vm.runInNewContext(`(function(){
    return ${temp};
  })`, context);
});

console.log(templateMap['templateA']()); // <h2>&lt;script/&gt;</h2>
